package pe.gob.mininter.dirandro.vaadin.panel;

import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import pe.gob.mininter.dirandro.exception.BaseException;
import pe.gob.mininter.dirandro.exception.InesperadoException;
import pe.gob.mininter.dirandro.exception.ValidacionException;
import pe.gob.mininter.dirandro.model.Usuario;
import pe.gob.mininter.dirandro.service.SeguridadService;
import pe.gob.mininter.dirandro.util.Constante;
import pe.gob.mininter.dirandro.util.HarecUtil;
import pe.gob.mininter.dirandro.vaadin.application.MainApplication;
import pe.gob.mininter.dirandro.vaadin.util.DirandroErrorEvent;
import pe.gob.mininter.dirandro.vaadin.util.Injector;

import com.vaadin.Application;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.event.ShortcutListener;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.terminal.gwt.server.WebBrowser;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.BaseTheme;

import eu.livotov.tpt.gui.widgets.TPTCaptcha;

public class PanelLogin extends CustomComponent implements ClickListener {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */
	
	@AutoGenerated
	private HorizontalLayout mainLayout;

	@AutoGenerated
	private VerticalLayout verticalLayout_5;

	@AutoGenerated
	private HorizontalLayout horizontalLayout_3;

	@AutoGenerated
	private VerticalLayout verticalLayout_2;

	@AutoGenerated
	private Panel pnlLogin;

	@AutoGenerated
	private VerticalLayout layoutLogin;

	@AutoGenerated
	private VerticalLayout verticalLayout_4;

	@AutoGenerated
	private Label lblMensaje03;

	@AutoGenerated
	private HorizontalLayout pnlBotonera;

	@AutoGenerated
	private Button btnLogin;

	@AutoGenerated
	private HorizontalLayout pnlCaptchaButtons;

	@AutoGenerated
	private Button btnRefreshCaptcha;

	@AutoGenerated
	private TextField txtCaptcha;

	@AutoGenerated
	private VerticalLayout pnlCaptcha;

	@AutoGenerated
	private GridLayout pnlDatos;

	@AutoGenerated
	private PasswordField txtClave;

	@AutoGenerated
	private Label lblClave;

	@AutoGenerated
	private TextField txtUsuario;

	@AutoGenerated
	private Label lblUsuario;

	@AutoGenerated
	private VerticalLayout verticalLayout_3;

	@AutoGenerated
	private Label lblMensaje05;

	@AutoGenerated
	private Label lblMensaje04;

	@AutoGenerated
	private Label lblMensaje02;

	@AutoGenerated
	private Label lblMensaje01;

	@AutoGenerated
	private VerticalLayout pnlLogo;

	@AutoGenerated
	private Embedded imgLogin;

	@AutoGenerated
	private VerticalLayout verticalLayout_1;

	@AutoGenerated
	private Panel pnlFondos;

	@AutoGenerated
	private VerticalLayout layoutFondo;

	@AutoGenerated
	private VerticalLayout pnlFondo;

	@AutoGenerated
	private Embedded imgFondo;

	private static final long serialVersionUID = 8280109496487749893L;

	private SeguridadService seguridadService;
//	private UbigeoService ubigeoService;
	
	//private CaptchaField captcha;
	
	private TPTCaptcha tptCaptcha;
	
	//private CaptchaField captchaField; 
	
	private Application app;
	
	private Window window;
	
	protected static final Log logger = LogFactory.getLog(PanelLogin.class);
	
	public PanelLogin(Window windowHarec) {
		super.attach();		
		seguridadService = Injector.obtenerServicio(SeguridadService.class);
		//ubigeoService = Injector.obtenerServicio(UbigeoService.class);
		buildMainLayout();
		setCompositionRoot(mainLayout);		
		btnLogin.addListener((ClickListener)this);
		
		btnRefreshCaptcha.setStyleName(BaseTheme.BUTTON_LINK);
		btnRefreshCaptcha.setIcon(Constante.ICONOS.RELOAD);
		btnRefreshCaptcha.setImmediate(true);
		btnRefreshCaptcha.addListener((ClickListener) this);
		
		lblUsuario.setStyleName("bold");
		lblClave.setStyleName("bold");
		txtUsuario.setValue("menriquez");
		txtClave.setValue("a");
		txtCaptcha.setImmediate(true);		
		window = windowHarec;
		
		txtUsuario.addShortcutListener(new ShortcutListener("", KeyCode.ENTER, null){

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void handleAction(Object sender, Object target) {
				handleActionEnter();
			}
			
		});
		txtClave.addShortcutListener(new ShortcutListener("", KeyCode.ENTER, null){

			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void handleAction(Object sender, Object target) {
				handleActionEnter();
			}
			
		});		
	}
	
	@Override
    public void attach() {
        super.attach();
        Application application = getApplication();
        MainApplication mainApplication = (MainApplication) application;
        mainApplication.setMainWindow(window);
		app = mainApplication.getMainWindow().getApplication();
		
		/*captchaField = new CaptchaField(app);
		captchaField.setCaption("Digite las palabras que aparecen en la Imagen");
		pnlCaptcha.addComponent(captchaField);*/
		
        tptCaptcha = new TPTCaptcha() {			
			private static final long serialVersionUID = 7195458609559799220L;

			@Override
			public void setCaptchaCode ( String code ) { 
				setCaptchaCode ( code, app);
			}
		};
		tptCaptcha.setImmediate(true);
		pnlCaptcha.addComponent(tptCaptcha);
    }
	
	private void handleActionEnter(){
		MainApplication mainApplication = (MainApplication)getApplication();
		try {
			login();
		} catch ( BaseException e) {
			logger.debug("baseex");
			com.vaadin.terminal.Terminal.ErrorEvent errorEvent = new DirandroErrorEvent(e);
			mainApplication.terminalError(errorEvent);
		} catch (Exception e) {
			logger.debug("generico");
			InesperadoException inesperadoException = new InesperadoException(Constante.CODIGO_MENSAJE.ERROR_GENERICO, null, e);
			com.vaadin.terminal.Terminal.ErrorEvent errorEvent = new DirandroErrorEvent(inesperadoException);
			mainApplication.terminalError(errorEvent);
		}
	}
	
	@Override
	public void buttonClick(ClickEvent event) {
		if(event.getButton().equals(btnLogin)){
			try {
				login();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		if(event.getButton().equals(btnRefreshCaptcha)){
			tptCaptcha.generateCaptchaCode(5);     
		}
	}
	
	private void login() throws NoSuchAlgorithmException{
		MainApplication mainApplication = (MainApplication)getApplication();
		String username = txtUsuario.getValue().toString();
		String password = txtClave.getValue().toString();
		
        if(StringUtils.isBlank(username))
        	throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Usuario"});
                
        if(StringUtils.isBlank(password))        
        	throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Password"});

        /*if (!tptCaptcha.verifyCaptchaCode((String) txtCaptcha.getValue())){
        	tptCaptcha.generateCaptchaCode(5);
        	throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_TEXTBOX, new Object[]{"Captcha Valido"});
        }*/
		
        username = username.toLowerCase();
        String hash512 = HarecUtil.returnSHA512(password);
        Usuario usuario = seguridadService.login(username, hash512);
        
        if(usuario != null){
        	WebApplicationContext context = ((WebApplicationContext) getApplication().getContext());
            WebBrowser webBrowser = context.getBrowser();
    		usuario.setTerminal(webBrowser.getAddress());
    		
        	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    		HttpServletRequest request = requestAttributes.getRequest();
    		HttpSession session = request.getSession(true);
    		session.setAttribute(Constante.SESION.USUARIO, usuario);
    		
    		mainApplication.cargarPanelPrincipal();
        }else{
        	tptCaptcha.generateCaptchaCode(5);
        	throw new ValidacionException(Constante.CODIGO_MENSAJE.VALIDAR_LOGIN, null);
        }
	}

	@AutoGenerated
	private HorizontalLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new HorizontalLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("800px");
		mainLayout.setMargin(false);
		
		// top-level component properties
		setWidth("100.0%");
		setHeight("800px");
		
		// verticalLayout_5
		verticalLayout_5 = buildVerticalLayout_5();
		mainLayout.addComponent(verticalLayout_5);
		mainLayout.setComponentAlignment(verticalLayout_5, new Alignment(48));
		
		return mainLayout;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_5() {
		// common part: create layout
		verticalLayout_5 = new VerticalLayout();
		verticalLayout_5.setImmediate(false);
		verticalLayout_5.setWidth("-1px");
		verticalLayout_5.setHeight("-1px");
		verticalLayout_5.setMargin(false);
		
		// horizontalLayout_3
		horizontalLayout_3 = buildHorizontalLayout_3();
		verticalLayout_5.addComponent(horizontalLayout_3);
		verticalLayout_5.setComponentAlignment(horizontalLayout_3,
				new Alignment(48));
		
		return verticalLayout_5;
	}

	@AutoGenerated
	private HorizontalLayout buildHorizontalLayout_3() {
		// common part: create layout
		horizontalLayout_3 = new HorizontalLayout();
		horizontalLayout_3.setImmediate(false);
		horizontalLayout_3.setWidth("-1px");
		horizontalLayout_3.setHeight("-1px");
		horizontalLayout_3.setMargin(true);
		horizontalLayout_3.setSpacing(true);
		
		// verticalLayout_1
		verticalLayout_1 = buildVerticalLayout_1();
		horizontalLayout_3.addComponent(verticalLayout_1);
		horizontalLayout_3.setComponentAlignment(verticalLayout_1,
				new Alignment(48));
		
		// verticalLayout_2
		verticalLayout_2 = buildVerticalLayout_2();
		horizontalLayout_3.addComponent(verticalLayout_2);
		horizontalLayout_3.setComponentAlignment(verticalLayout_2,
				new Alignment(48));
		
		return horizontalLayout_3;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_1() {
		// common part: create layout
		verticalLayout_1 = new VerticalLayout();
		verticalLayout_1.setImmediate(false);
		verticalLayout_1.setWidth("-1px");
		verticalLayout_1.setHeight("-1px");
		verticalLayout_1.setMargin(false);
		verticalLayout_1.setSpacing(true);
		
		// pnlFondos
		pnlFondos = buildPnlFondos();
		verticalLayout_1.addComponent(pnlFondos);
		
		return verticalLayout_1;
	}

	@AutoGenerated
	private Panel buildPnlFondos() {
		// common part: create layout
		pnlFondos = new Panel();
		pnlFondos.setImmediate(false);
		pnlFondos.setWidth("-1px");
		pnlFondos.setHeight("-1px");
		
		// layoutFondo
		layoutFondo = buildLayoutFondo();
		pnlFondos.setContent(layoutFondo);
		
		return pnlFondos;
	}

	@AutoGenerated
	private VerticalLayout buildLayoutFondo() {
		// common part: create layout
		layoutFondo = new VerticalLayout();
		layoutFondo.setImmediate(false);
		layoutFondo.setWidth("-1px");
		layoutFondo.setHeight("-1px");
		layoutFondo.setMargin(false);
		
		// pnlFondo
		pnlFondo = buildPnlFondo();
		layoutFondo.addComponent(pnlFondo);
		
		return layoutFondo;
	}

	@AutoGenerated
	private VerticalLayout buildPnlFondo() {
		// common part: create layout
		pnlFondo = new VerticalLayout();
		pnlFondo.setImmediate(false);
		pnlFondo.setWidth("-1px");
		pnlFondo.setHeight("-1px");
		pnlFondo.setMargin(false);
		
		// imgFondo
		imgFondo = new Embedded();
		imgFondo.setImmediate(false);
		imgFondo.setWidth("500px");
		imgFondo.setHeight("500px");
		imgFondo.setSource(new ThemeResource("img/imagen.jpg"));
		imgFondo.setType(1);
		imgFondo.setMimeType("image/jpg");
		pnlFondo.addComponent(imgFondo);
		
		return pnlFondo;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_2() {
		// common part: create layout
		verticalLayout_2 = new VerticalLayout();
		verticalLayout_2.setImmediate(false);
		verticalLayout_2.setWidth("-1px");
		verticalLayout_2.setHeight("-1px");
		verticalLayout_2.setMargin(false);
		verticalLayout_2.setSpacing(true);
		
		// pnlLogin
		pnlLogin = buildPnlLogin();
		verticalLayout_2.addComponent(pnlLogin);
		
		return verticalLayout_2;
	}

	@AutoGenerated
	private Panel buildPnlLogin() {
		// common part: create layout
		pnlLogin = new Panel();
		pnlLogin.setImmediate(false);
		pnlLogin.setWidth("-1px");
		pnlLogin.setHeight("500px");
		
		// layoutLogin
		layoutLogin = buildLayoutLogin();
		pnlLogin.setContent(layoutLogin);
		
		return pnlLogin;
	}

	@AutoGenerated
	private VerticalLayout buildLayoutLogin() {
		// common part: create layout
		layoutLogin = new VerticalLayout();
		layoutLogin.setImmediate(false);
		layoutLogin.setWidth("100.0%");
		layoutLogin.setHeight("100.0%");
		layoutLogin.setMargin(false);
		layoutLogin.setSpacing(true);
		
		// pnlLogo
		pnlLogo = buildPnlLogo();
		layoutLogin.addComponent(pnlLogo);
		layoutLogin.setComponentAlignment(pnlLogo, new Alignment(24));
		
		// verticalLayout_3
		verticalLayout_3 = buildVerticalLayout_3();
		layoutLogin.addComponent(verticalLayout_3);
		
		// pnlDatos
		pnlDatos = buildPnlDatos();
		layoutLogin.addComponent(pnlDatos);
		layoutLogin.setComponentAlignment(pnlDatos, new Alignment(48));
		
		// pnlCaptcha
		pnlCaptcha = new VerticalLayout();
		pnlCaptcha.setCaption("Digite los Valores que aparecen en la Imagen");
		pnlCaptcha.setImmediate(false);
		pnlCaptcha.setWidth("100.0%");
		pnlCaptcha.setHeight("60px");
		pnlCaptcha.setMargin(false);
		layoutLogin.addComponent(pnlCaptcha);
		layoutLogin.setComponentAlignment(pnlCaptcha, new Alignment(20));
		
		// pnlCaptchaButtons
		pnlCaptchaButtons = buildPnlCaptchaButtons();
		layoutLogin.addComponent(pnlCaptchaButtons);
		layoutLogin.setComponentAlignment(pnlCaptchaButtons, new Alignment(20));
		
		// pnlBotonera
		pnlBotonera = buildPnlBotonera();
		layoutLogin.addComponent(pnlBotonera);
		layoutLogin.setComponentAlignment(pnlBotonera, new Alignment(20));
		
		// verticalLayout_4
		verticalLayout_4 = buildVerticalLayout_4();
		layoutLogin.addComponent(verticalLayout_4);
		layoutLogin.setComponentAlignment(verticalLayout_4, new Alignment(6));
		
		return layoutLogin;
	}

	@AutoGenerated
	private VerticalLayout buildPnlLogo() {
		// common part: create layout
		pnlLogo = new VerticalLayout();
		pnlLogo.setImmediate(false);
		pnlLogo.setWidth("400px");
		pnlLogo.setHeight("106px");
		pnlLogo.setMargin(false);
		
		// imgLogin
		imgLogin = new Embedded();
		imgLogin.setImmediate(false);
		imgLogin.setWidth("100.0%");
		imgLogin.setHeight("100.0%");
		imgLogin.setSource(new ThemeResource("img/logo.png"));
		imgLogin.setType(1);
		imgLogin.setMimeType("image/png");
		pnlLogo.addComponent(imgLogin);
		
		return pnlLogo;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_3() {
		// common part: create layout
		verticalLayout_3 = new VerticalLayout();
		verticalLayout_3.setImmediate(false);
		verticalLayout_3.setWidth("-1px");
		verticalLayout_3.setHeight("-1px");
		verticalLayout_3.setMargin(true);
		
		// lblMensaje01
		lblMensaje01 = new Label();
		lblMensaje01.setStyleName("bold");
		lblMensaje01.setImmediate(false);
		lblMensaje01.setWidth("157px");
		lblMensaje01.setHeight("-1px");
		lblMensaje01.setValue("Sistema de DIRINCRI");
		verticalLayout_3.addComponent(lblMensaje01);
		
		// lblMensaje02
		lblMensaje02 = new Label();
		lblMensaje02.setImmediate(false);
		lblMensaje02.setWidth("-1px");
		lblMensaje02.setHeight("-1px");
		lblMensaje02
				.setValue("El Sistema de la la Dirincri Permite el registro de investiganción");
		verticalLayout_3.addComponent(lblMensaje02);
		
		// lblMensaje04
		lblMensaje04 = new Label();
		lblMensaje04.setImmediate(false);
		lblMensaje04.setWidth("-1px");
		lblMensaje04.setHeight("-1px");
		lblMensaje04
				.setValue("de una denuncia y sus componentes tales delitos, involucrados,");
		verticalLayout_3.addComponent(lblMensaje04);
		
		// lblMensaje05
		lblMensaje05 = new Label();
		lblMensaje05.setImmediate(false);
		lblMensaje05.setWidth("-1px");
		lblMensaje05.setHeight("-1px");
		lblMensaje05
				.setValue("vehículos, armas, drogas, especies entre otros.  ");
		verticalLayout_3.addComponent(lblMensaje05);
		
		return verticalLayout_3;
	}

	@AutoGenerated
	private GridLayout buildPnlDatos() {
		// common part: create layout
		pnlDatos = new GridLayout();
		pnlDatos.setImmediate(false);
		pnlDatos.setWidth("350px");
		pnlDatos.setHeight("-1px");
		pnlDatos.setMargin(false);
		pnlDatos.setSpacing(true);
		pnlDatos.setColumns(2);
		pnlDatos.setRows(3);
		
		// lblUsuario
		lblUsuario = new Label();
		lblUsuario.setImmediate(false);
		lblUsuario.setWidth("-1px");
		lblUsuario.setHeight("-1px");
		lblUsuario.setValue("Usuario");
		pnlDatos.addComponent(lblUsuario, 0, 0);
		pnlDatos.setComponentAlignment(lblUsuario, new Alignment(34));
		
		// txtUsuario
		txtUsuario = new TextField();
		txtUsuario.setImmediate(false);
		txtUsuario.setWidth("-1px");
		txtUsuario.setHeight("-1px");
		pnlDatos.addComponent(txtUsuario, 1, 0);
		pnlDatos.setComponentAlignment(txtUsuario, new Alignment(33));
		
		// lblClave
		lblClave = new Label();
		lblClave.setImmediate(false);
		lblClave.setWidth("-1px");
		lblClave.setHeight("-1px");
		lblClave.setValue("Contraseña");
		pnlDatos.addComponent(lblClave, 0, 1);
		pnlDatos.setComponentAlignment(lblClave, new Alignment(34));
		
		// txtClave
		txtClave = new PasswordField();
		txtClave.setImmediate(false);
		txtClave.setWidth("-1px");
		txtClave.setHeight("-1px");
		pnlDatos.addComponent(txtClave, 1, 1);
		pnlDatos.setComponentAlignment(txtClave, new Alignment(33));
		
		return pnlDatos;
	}

	@AutoGenerated
	private HorizontalLayout buildPnlCaptchaButtons() {
		// common part: create layout
		pnlCaptchaButtons = new HorizontalLayout();
		pnlCaptchaButtons.setImmediate(false);
		pnlCaptchaButtons.setWidth("-1px");
		pnlCaptchaButtons.setHeight("-1px");
		pnlCaptchaButtons.setMargin(false);
		pnlCaptchaButtons.setSpacing(true);
		
		// txtCaptcha
		txtCaptcha = new TextField();
		txtCaptcha.setImmediate(false);
		txtCaptcha.setWidth("-1px");
		txtCaptcha.setHeight("-1px");
		pnlCaptchaButtons.addComponent(txtCaptcha);
		
		// btnRefreshCaptcha
		btnRefreshCaptcha = new Button();
		btnRefreshCaptcha.setCaption("Button");
		btnRefreshCaptcha.setImmediate(true);
		btnRefreshCaptcha.setWidth("-1px");
		btnRefreshCaptcha.setHeight("-1px");
		pnlCaptchaButtons.addComponent(btnRefreshCaptcha);
		pnlCaptchaButtons.setComponentAlignment(btnRefreshCaptcha,
				new Alignment(48));
		
		return pnlCaptchaButtons;
	}

	@AutoGenerated
	private HorizontalLayout buildPnlBotonera() {
		// common part: create layout
		pnlBotonera = new HorizontalLayout();
		pnlBotonera.setImmediate(false);
		pnlBotonera.setWidth("350px");
		pnlBotonera.setHeight("-1px");
		pnlBotonera.setMargin(false);
		
		// btnLogin
		btnLogin = new Button();
		btnLogin.setCaption("Login");
		btnLogin.setImmediate(true);
		btnLogin.setWidth("-1px");
		btnLogin.setHeight("-1px");
		pnlBotonera.addComponent(btnLogin);
		pnlBotonera.setComponentAlignment(btnLogin, new Alignment(20));
		
		return pnlBotonera;
	}

	@AutoGenerated
	private VerticalLayout buildVerticalLayout_4() {
		// common part: create layout
		verticalLayout_4 = new VerticalLayout();
		verticalLayout_4.setImmediate(false);
		verticalLayout_4.setWidth("-1px");
		verticalLayout_4.setHeight("-1px");
		verticalLayout_4.setMargin(false);
		
		// lblMensaje03
		lblMensaje03 = new Label();
		lblMensaje03.setImmediate(false);
		lblMensaje03.setWidth("200px");
		lblMensaje03.setHeight("-1px");
		lblMensaje03.setValue("© Ministerio del Interior 2013     ");
		verticalLayout_4.addComponent(lblMensaje03);
		verticalLayout_4.setComponentAlignment(lblMensaje03, new Alignment(6));
		
		return verticalLayout_4;
	}	

}
